package com.mn.ble.c.ad

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mn.ble.c.R

class BleAdapter : RecyclerView.Adapter<BleAdapter.ViewHolder>() {

    var mCallback: IRvCallback<BleBean>? = null
    private val mList: MutableList<BleBean> = ArrayList()


    fun contains(device: BleBean?): Boolean {
        for (b in mList) {
            if (b.device.address.equals(device!!.device.address)) {
                return true
            }
        }
        return false
    }

    fun addData(data: BleBean) {
        mList.add(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_ble, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("MissingPermission", "SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data = mList.get(position)

        holder.t1.setText(data.device.name + "  " + data.device.address + "  " + data.device.type + "  " + data.device.bondState)
        //-127 ..126
        holder.t2.setText("rssi:" + data.result.rssi)


        //TODO 这里过滤广播 !!!!!
        val manufacturerData: ByteArray? =  data.result.scanRecord?.getManufacturerSpecificData(0x0001)
        if (manufacturerData != null && manufacturerData.isNotEmpty()) {
            val deviceIdentifier = String(manufacturerData)
            holder.t3.text = deviceIdentifier
        }else{
            holder.t3.text = "none"
        }

        holder.t4.visibility = View.GONE

        holder.itemView.setOnClickListener {
            mCallback?.onItemClick(data, position)
        }
    }

    override fun getItemCount(): Int {
        return mList.size
    }


    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val t1 = itemView.findViewById<TextView>(R.id.v_title1)
        val t2 = itemView.findViewById<TextView>(R.id.v_title2)
        val t3 = itemView.findViewById<TextView>(R.id.v_title3)
        val t4 = itemView.findViewById<TextView>(R.id.v_title4)
    }
}